package com.zd.utils;

import com.zd.domain.TokenState;
import io.jsonwebtoken.*;

import java.util.Date;
import java.util.UUID;

public class JWTUtils {

    private static String signature = "4ad8c8509d03753304a447d998ee27fc";

    //生成token方法
    public static String createJWT(long time, int id){
        JwtBuilder jwtBuilder = Jwts.builder();

        String token = jwtBuilder.setHeaderParam("typ","jwt")
                .setHeaderParam("alg","HS256")
                .claim("id",id)
                .setSubject("jwt-token")
                .setExpiration(new Date(System.currentTimeMillis()+time))
                .setId(UUID.randomUUID().toString())
                .signWith(SignatureAlgorithm.HS256,signature)
                .compact();
        return token;
    }

    //解析token
    public static TokenState parseJWT(String token){
        JwtParser parser = Jwts.parser();

        TokenState tokenState = new TokenState();

        Jws<Claims> claimsJws = null;
        try {
            claimsJws = parser.setSigningKey(signature).parseClaimsJws(token);
        }catch (ExpiredJwtException e){
            //超时异常
            tokenState.setNum(-1);
        }catch (UnsupportedJwtException e){
            throw new RuntimeException(e);
        }catch (MalformedJwtException e){
            throw new RuntimeException(e);
        }catch (SignatureException e){
            //签名异常
            tokenState.setNum(-2);
        }catch (IllegalArgumentException e){
            //非法参数异常
        }
        if (claimsJws != null){
            Claims claims = claimsJws.getBody();

            int userID = (int) claims.get("id");

            tokenState.setUserID(userID);

        }

        return tokenState;

    }

}
